package com.rentapark.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import services.SearchService;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import com.google.android.gcm.GCMRegistrar;
import com.google.android.maps.GeoPoint;

import data.DB;
import static data.CommonUtilities.SENDER_ID;
import com.google.android.gcm.GCMRegistrar;

/*this is the main screen of the application, from here you can choose if you want
 * to seak a parking spot or if you want to offer your parking spot for rent
 */
public class MainScreen extends Activity{
	//for GCM:
	private String TAG = "** pushAndroidActivity **";
	private TextView mDisplay;
		
	final MainScreen thisActivity = this;
	DB db_instance;
	static final int PROGRESS_DIALOG = 0;
	ProgressDialog progressDialog;
	
//handler for handling responses from the server after the user logs in
	private final Handler handler = new Handler() {  
		public void handleMessage(Message msg) { 
			progressDialog.dismiss(); 
			Log.d("login","got response");
		} 
	}; 
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		//get DB instance
		db_instance=DB.getInstance();
		setContentView(R.layout.main_screen);
		Log.d("mainScreen","oncreate");
		//if a deal has been closed and user enters mainScreen again..paramters are initialized
		if(db_instance.dealClosed==true)
		{
			db_instance.dealClosed=false;
			db_instance.userDealPhone="";
			db_instance.userDealId=-1;
			db_instance.spotRentId=-1;
		}
			
//GCM commands for registering the device
		checkNotNull(SENDER_ID, "SENDER_ID");
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		mDisplay = (TextView) findViewById(R.id.display);
		final String regId = GCMRegistrar.getRegistrationId(this);
		Log.i(TAG, "registration id =====  "+regId);
		db_instance.registration_id=regId;
		Log.d("registration- service",db_instance.registration_id);
		

		if (regId.equals("")) {
			GCMRegistrar.register(this, SENDER_ID);
		} else {
			Log.v(TAG, "Already registered");
		}

		mDisplay.setText("ffffff        "+regId);
		
	
		//checking if the user is a new user or if it has already signed up..
		SharedPreferences ref = getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
		//if "my_id" != -1 then the user is not a new user and he only has to login
		if(!(ref.getString("my_id", "-1").equals("-1")))
		{
			//save all user's data (already saved in preferences file ) in the database
			db_instance.userID=Double.parseDouble(ref.getString("my_id", "-1"));
			db_instance.userName=ref.getString("userName", "-1");
			db_instance.userPhone=ref.getString("userPhone", "-1");
			db_instance.UserCarNo=ref.getString("UserCarNo", "-1");
			
		}
		//perform login
		
		PerformLogin();
		//defining search button and rent button
		Button SearchButton = (Button)this.findViewById(R.id.SearchButton);
		Button RentButton = (Button)this.findViewById(R.id.RentButton);
		//if user chooses search button then start service "SearchService"
		SearchButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startService(new Intent(MainScreen.this,SearchService.class));
			}
		});
		//if user chooses rent button then start activity "RentScreen"
		RentButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(thisActivity, RentScreen.class);
				startActivity(intent);
			}
		});



	}
	//method for checking that an object is not null
	private void checkNotNull(Object reference, String name) {
		if (reference == null) {
			throw new NullPointerException(
					getString(R.string.error_config, name));
		}
	}
	//method for defining the optionsMenu in the activity
	public boolean onCreateOptionsMenu(Menu menu) { 
		super.onCreateOptionsMenu(menu); 
		MenuInflater inflater = getMenuInflater(); 
		inflater.inflate(R.menu.menu, menu); 
		return true;

	}
	//method for defining the items in the Menu Item
	public boolean onOptionsItemSelected(MenuItem item) { 
		switch (item.getItemId()) { 
		/*item for the user that offered a parking spot, it  
		 * takes him to a list activity where he can see all the requests he got for each offer he made
		 * with information about the request's sender
		 */
		case R.id.item11: 
			Intent intent = new Intent(thisActivity, OwnerList.class);
			startActivity(intent);
			return true; 
		/*item for viewing the user's profile*/
		case R.id.item13: 
			Intent intentP = new Intent(thisActivity, Profile.class);
			startActivity(intentP);
			return true; 


		}
		return super.onOptionsItemSelected(item); 
	}
	/*method for performing login. The method sends an http post message to the server
	 * sending in an xml format the next information: user id. Then the servre will know the user has
	 * performed login
	 */
	private void PerformLogin(){
		final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {   
			public String handleResponse(HttpResponse response) {    
				//StatusLine status = response.getStatusLine();        
				HttpEntity entity = response.getEntity();          
				String result = null; 
				try { 
					result = data.CommonUtilities.inputStreamToString(entity.getContent());

					Message message = new Message();     
					Bundle bundle = new Bundle();         
					bundle.putString("RESPONSE", result); 
					message.setData(bundle); 
					handler.sendMessage(message);

				} catch (IOException e) { 
					Log.e("Class6",  " ", e); 
				} 
				return result; 
			} 
		}; 


		this.progressDialog = ProgressDialog.show(this, "executing", "          LOGIN"); 
		// create and run the thread that perform the request and handle the response
		new Thread() {                          
			@Override 
			public void run() { 
				HttpClient httpclient = new DefaultHttpClient();
				String url="http://";
				url+=db_instance.instanceDNS;
				url+=":8080/ParkAndLetPark/NewUser";
				HttpPost httppost = new HttpPost(url);
				try {
					try{
						DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

						DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();

						//creating a new instance of a DOM to build a DOM tree.
						Document doc = docBuilder.newDocument();
						Element Response = doc.createElement("MSG_TYPE");
						Response.appendChild(doc.createTextNode("LOGIN"));
						doc.appendChild(Response);

						Element type=doc.createElement("LOGIN_TYPE");
						type.appendChild(doc.createTextNode("LOGIN_NOT_NEW"));
						Response.appendChild(type);
						SharedPreferences ref= getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
						int myID=Integer.parseInt(ref.getString("my_id", "0"));

						Element id=doc.createElement("USER_ID");
						id.appendChild(doc.createTextNode(Integer.toString(myID)));
						type.appendChild(id);

						Element regId=doc.createElement("REGISTRATION_ID");
						regId.appendChild(doc.createTextNode(db_instance.registration_id));
						id.appendChild(regId);

						TransformerFactory factory = TransformerFactory.newInstance();
						Transformer transformer = factory.newTransformer();

						transformer.setOutputProperty(OutputKeys.INDENT, "yes");

						StringWriter sw = new StringWriter();
						StreamResult result = new StreamResult(sw);
						DOMSource source = new DOMSource(doc);
						transformer.transform(source, result);
						String xmlString = sw.toString();
						Log.d("xmlString","^^^^^^^"+xmlString);
						StringEntity se = new StringEntity(xmlString); //XML as a string
						se.setContentType("text/xml"); //declare it as XML
						httppost.setEntity(se);

						String response = httpclient.execute(httppost,responseHandler);

					}
					catch (ClientProtocolException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (IOException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (TransformerConfigurationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}




				}
				catch(Exception e)
				{
					Log.e("LOGTAG", " " , e); 
				}
			}

		}.start(); 


	}
	//onPause method
	public void onPause(){
		super.onPause();
		Log.d("mainScreen","onpause");
		//GCMRegistrar.unregister(this);
		stopService(new Intent(MainScreen.this,SearchService.class));

	}
	public void onStop(){
		super.onStop();
		Log.d("mainScreen","onStop");
	}


}
